package com.dbh.company.zk;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.zookeeper.KeeperException;

import java.io.*;
import java.util.Arrays;
import java.util.List;

/**
 * @Description
 * @Date 2019/10/24 16:54
 * @Auther wanghonggang
 */
public class Learn {

    public static String BASE_PATH = "/groupCenter/balanceapi";
    public static String FILE_PATH = "/Users/dongbanghui/work/file/temp.log";

    public static BaseZookeeper zookeeper = new BaseZookeeper();

    public static void main(String[] args) throws Exception {

        zookeeper.connectZookeeper("zk01-test.lianjia.com:2181,zk02-test.lianjia.com:2181,zk03-test.lianjia.com:2181", "jichu", "bdcccaccB9");
        //删除目录下所有
//        deletePath(BASE_PATH, "/groupCenter/balanceapi");
//        readFile();
        //设置值
//        setValue(BASE_PATH);
        //获取目录下所有
//        getAllDataFromPath("/jichu3/dubbo");
        createNodePath("jichu3/cprd/freeform_student");


        System.out.println("Success!");
    }

    /**
     *
     * 标准格式
     *ordernew_all/degrade/InternationalRemoteSrevice.checkIdentyCardNew==========={"degrade":0}
     ordernew_all/degrade/InvoiceService.getInvoiceCodeList==========={"degrade":0}
     ordernew_all/degrade/ShipmentService.setCoudanEntry==========={"degrade":0}
     ordernew_all/degrade/AddressRemoteService.getAreaInfoForOversea==========={degrade:0}
     ordernew_all/degrade/OrderRemoteService.cancelSkuScaleBuyPrice==========={degrade:0}
     ordernew_all/degrade/ShipmentService.setFreightRiskInfos==========={degrade:0}
     * @throws Exception
     */
    public static void setValue(String basePath) throws Exception {
        String resultInfo = readFile(FILE_PATH);
        List<String> list = Arrays.asList(resultInfo.split("/temp/banghui/balanceapi"));
        System.out.println("all size============================" + list.size());
        for (String item : list) {
            if (StrUtil.isBlank(item)) {
                continue;
            }
            String [] keyValue = item.split("=");
            String [] keys = keyValue[0].split("/");

                StringBuilder pathSB = new StringBuilder();
            //如果有basePath则使用base，没有的话直接从/走起
            pathSB.append(basePath);
            //创建该节点
            for (String temp : keys) {
                if (StrUtil.isNotBlank(temp)) {
                    pathSB.append("/").append(temp);
                    if (!zookeeper.exists(pathSB.toString())) {
                        zookeeper.createNode(pathSB.toString());
                    }
                }
            }
            System.out.println(BASE_PATH + keyValue[0] + "=" + (keyValue.length == 2 ? keyValue[1] : ""));
            zookeeper.setData(BASE_PATH + keyValue[0], keyValue.length == 2 ? keyValue[1] : "");
//            zookeeper.setData(BASE_PATH + keyValue[0], keyValue.length == 2 ? keyValue[1] : "");
//            break;
        }
    }

    public static void createNodePath(String path)  throws Exception {
        if (!zookeeper.exists(path)) {
            zookeeper.createNode(path);
        }
    }

    public static String readFile(String strFile){
        try{
            InputStream is = new FileInputStream(strFile);
            int iAvail = is.available();
            byte[] bytes = new byte[iAvail];
            is.read(bytes);
            String info = new String(bytes, "utf-8");
            is.close();
            return info;
        }catch(Exception e){
            e.printStackTrace();
        }
        return "";
    }


    public static void readFileByLine(String strFile){
        try {
            File file = new File(strFile);
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
            String strLine = null;
            int lineCount = 1;
            while(null != (strLine = bufferedReader.readLine())){
                System.out.println(("第[" + lineCount + "]行数据:[" + strLine + "]"));
                lineCount++;
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 递归删除数据
     * @param filePath
     * @throws Exception
     */
    public static void deletePath(String basePath, String filePath) throws Exception {
        List<String> children = zookeeper.getChildren(filePath);
        if (children != null || children.size() > 0) {
            //删除叶子
            for (String child : children) {
                deletePath(basePath, filePath + "/" + child);
            }
        }

        //删除所有的叶子节点。在删除根节点,最初节点不删除
        if (!basePath.equals(filePath)) {
            zookeeper.deleteNode(filePath);
        }

    }

    public static List<String> getAllDataFromPath(String filePath) throws Exception {
        List<String> children = zookeeper.getChildren(filePath);
        if (children == null || children.size() == 0) {
//            FileUtil.writeUtf8String(filePath + "=" + zookeeper.getData(filePath) + System.lineSeparator(), "F:\\work\\file\\zk.txt");
            System.out.println(filePath + "=" + zookeeper.getData(filePath));
            return null;
        }
        for (String child : children) {
            getAllDataFromPath(filePath + "/" + child);
        }
        return children;
    }
}
